package com.app.beans;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by zhangzhiling on 2017/1/16.
 */
public class ListFrame extends JFrame{

    private  static final int DEFAULT_WIDTH = 400;




    private static final int DEFAULT_HEGHT = 300;

    private JPanel listPanel;

    private JList wordList;

    private JLabel label;

    private JPanel buttonPanel;

    private ButtonGroup group;

    private String prefix = "The ";

    private String suffix = "fox jumps over the lazy dog.";

    public ListFrame(){
        setTitle("ListTest");
        setSize(DEFAULT_WIDTH, DEFAULT_HEGHT);

        String[] words={"quick","brown","hungry","wild","silent","huge","private",
                       "abstract","static", "final"};
        wordList = new JList(words);
        wordList.setVisibleRowCount(4);  //获取或设置列表在没有滚动条时显示的默认行数
        JScrollPane scorllPane = new JScrollPane(wordList);
        listPanel = new JPanel();
        listPanel.add(scorllPane);
//        wordList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        wordList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {  //向列表添加一个在每次选择结果发生变化时会被告知的监听器
                Object[] values = wordList.getSelectedValues();  // 获取所有的选定值
                StringBuilder text = new StringBuilder(prefix);
                for(int i=0; i<values.length; i++){
                    String word = (String)values[i];
                    text.append(word);
                    text.append(" ");
                }
                text.append(suffix);
                label.setText(text.toString());
            }
        });
        buttonPanel = new JPanel();
        group = new ButtonGroup();
        makeButton("Vertical", JList.VERTICAL);
        makeButton("Vertical Wrap", JList.VERTICAL_WRAP);
        makeButton("Horizontal  Wrap", JList.HORIZONTAL_WRAP);

        add(listPanel, BorderLayout.NORTH);
        label = new JLabel(prefix + suffix);
        add(label, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }


    public void makeButton(String label, final int orientation){

        JRadioButton button = new JRadioButton(label);
        buttonPanel.add(button);
        if(group.getButtonCount() == 0) button.setSelected(true);
        group.add(button);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
              wordList.setLayoutOrientation(orientation); //设置方向布局
              listPanel.revalidate();
            }
        });

    }
}
